package com.scalar.chiptrack.adaptor.sitime;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.InventoryLot;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.XLSParserImpl;
import com.scalar.chiptrack.adaptor.dao.InventoryLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.ScalarException;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Date;
import java.io.File;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 22 Jan, 2010
 * Time: 1:41:21 PM
 */
public class CarsemFGParser extends JobHandler implements AdaptorConstants
{
    private HashMap<String, InventoryLot> m_fgDataMap       = new HashMap<String, InventoryLot>();

    private Logger m_parserLogger       = null;
    private String m_dataOutputDir      = null;

    public  CarsemFGParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = AdaptorUtils.getDataOutputDir( VENDOR_NAME_CARCEM , LOCATION_TYPE_FINISHED_GOODS );

            if ( m_dataOutputDir != null )
            {
                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );

                m_parserLogger= AdaptorUtils.getDataParserLogger( m_dataOutputDir,VENDOR_NAME_CARCEM );

                AdaptorUtils.setLogger( m_parserLogger );
                InventoryLotDAO.setLogger(m_parserLogger);
            }
        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading CARCEM output directory details from database, Exception: " + se );
            System.out.println( "ERROR!! ERROR!! ERROR!! Exception while loading CARCEM output directory details from database, Exception: " + se );
        }
    }
    public static void main( String args[] ) throws Exception
    {
        try
        {
            new CarsemFGParser().execute();
        }
        catch ( Exception e )
        {
            throw e;
        }
    }
    public void execute() throws Exception
    {
        AdaptorUtils.printHeader( VENDOR_NAME_CARCEM, CONSTANT_PARSER );

        File doneDestDir = new File( m_dataOutputDir + "/done" );
        File dataoutDir  = new File( m_dataOutputDir );

        File[] fileList = dataoutDir.listFiles();

        if ( ( fileList == null ) || (fileList.length <= 3))
        {
            log("No file found in directory: " + dataoutDir);
            System.out.println("No file found in directory: " + dataoutDir );
            throw new ScalarException("No file found in directory: " + dataoutDir+ "----\n\n" );
        }

        ArrayList<File> successFileList = new ArrayList<File>();

        boolean success = false;

        for ( int i = 0; i < fileList.length; i++ )
        {
            if ( fileList[i].isDirectory() == true )
            {
                continue;
            }

            try
            {
                if ( fileList[i].getName().startsWith( CarsemPOP3Adaptor.FILE_NAME_DAILY_WIP )  || fileList[i].getName().indexOf( CarsemPOP3Adaptor.FILE_NAME_DAILY_WIP )  != -1)
                {
                     parseFGWipReport( fileList[i].getAbsolutePath() );

                    successFileList.add(fileList[i]);
                }

               success = true;
            }
            catch (Exception e)
            {
                success = false;
                log("Exception while parsing file: " + fileList[i].getAbsolutePath() + "\nException: " + e);
                e.printStackTrace();
                throw e;
            }
        }

       // to save the Finished Goods lot tables
       try
       {
           if ( m_fgDataMap.isEmpty() == false )
           {
               log(" Updating Finished Goods Lot Information");
               InventoryLotDAO.saveInventoryLot( null, m_fgDataMap.values().iterator(), LOCATION_TYPE_FG, VENDOR_NAME_CARCEM );
               success = true;
           }
           else
           {
               InventoryLotDAO.closeInventoryLot(null, LOCATION_TYPE_FG, VENDOR_NAME_CARCEM );
           }
      }
      catch (ScalarException se)
      {
          success = false;
          se.printStackTrace();
          log("ERROR!! ERROR!! ERROR!! Could not update Finished Goods Lot information into database: " + se);
          throw se;
      }

        // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
        AdaptorDAO.sendAllNotifications( VENDOR_NAME_CARCEM,true, true, true );

        // To Close the Drop Out Lots
        AdaptorDAO.closeDropOutLots( VENDOR_NAME_CARCEM );

        int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( CarsemPOP3Adaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);
        // transaction 9
        try
        {
            if (success)
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, CarsemPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println("SUCCESSFULLY UPDATED IN THE DATABASE");
            }
        }
        catch (ScalarException se)
        {
            success = false;  //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, CarsemPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log("WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se);
            throw se;
        }

        // Step 10
        // Move the successful files to 'done' directory
        if (success)
        {
            AdaptorUtils.moveFilesToDone( successFileList, doneDestDir);
        }
    }

    private void parseFGWipReport (String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result            = null;

        InventoryLot inventoryLot  = null;
        String partNumber       = null;
        String fabLotNumber     = null;
        int dieQtyIn            = 0;
        String dateIn           = null;


        try
        {
            File detailWipFile = new File( fileName );
            if ( !detailWipFile.exists() )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            Parser parser = ParserFactory.getXLSParser( detailWipFile );

            ((XLSParserImpl)parser).setHeaderRowIdx(6);
            ((XLSParserImpl)parser).setDataStartRowIdx(7);

            log( "\nFound " + fileName );
            log( "\nParsing the file for Drop Ship Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for Drop Ship Report..." );

            result = parser.parse();

            while ( result.next() )
            {
                partNumber      = result.getString("Device");
                fabLotNumber    = result.getString("Lot#");

                if ( partNumber != null && partNumber.trim().length() > 0 && fabLotNumber != null && fabLotNumber.trim().length() > 0 )
                {
                    if ( partNumber.endsWith("TUS") )
                    {
                        partNumber = partNumber.substring(0, partNumber.lastIndexOf("-"));
                        //System.out.println("partNumber = " + partNumber);
                    }
                    if ( fabLotNumber.indexOf("@") != -1 )
                    {
                        fabLotNumber = fabLotNumber.split("@")[0];
                    }
                    try
                    {
                        dieQtyIn = result.getInt("FG qty") ;
                    }
                    catch(NumberFormatException nfe)
                    {
                        dieQtyIn = 0;
                    }

                    if ( dieQtyIn > 0 )
                    {
                        if ( result.getString( "Date to FG") != null )
                        {
                            dateIn = StringUtils.formatDate( result.getString( "Date to FG"),  "yyyy-MMM-dd", "MM/dd/yyyy" );
                        }
                        if ( partNumber.indexOf("-TUS") != -1 )
                        {
                            partNumber = partNumber.substring(0, partNumber.indexOf("-TUS") );
                        }
                        log("IN FG lotNumber = " + fabLotNumber);
                        inventoryLot = m_fgDataMap.get( fabLotNumber + partNumber );

                        if( inventoryLot == null )
                        {
                            inventoryLot = new InventoryLot( VENDOR_NAME_CARCEM,  LOCATION_TYPE_FG);
                            m_fgDataMap.put(  fabLotNumber + partNumber , inventoryLot );
                        }
                        int quantity = 0;
                        if (inventoryLot.getQtyIn() != null )
                        {
                            try
                            {
                                quantity = Integer.parseInt(inventoryLot.getQtyIn() );
                            }
                            catch (NumberFormatException nfe)
                            {
                                quantity = 0;
                            }
                            quantity += dieQtyIn;
                        }
                        else
                        {
                            quantity = dieQtyIn;
                        }
                        inventoryLot.setPartNumber( partNumber );
                        inventoryLot.setLotNumber( fabLotNumber );
                        inventoryLot.setFabLotNumber( fabLotNumber );
                        inventoryLot.setQtyIn( quantity+"" );
                        inventoryLot.setDateIn( dateIn );
                        inventoryLot.setStatus(LOT_STATUS_RUNNING);
                        inventoryLot.setLotCategory( LOT_CATEGORY_TYPE_PROD );
                        inventoryLot.setDateCode( result.getString("D/C") );
                        inventoryLot.setPkgType( result.getString("Package") );
                        inventoryLot.setCustomerPO(result.getString("PO# / Release#"));
                    }
                }
            }
        }
        catch(Exception e )
        {
            e.printStackTrace();
            throw e;
        }
    }

    private void log( String message )
    {
      if ( message == null ) return;

      if ( m_parserLogger != null )
      {
          m_parserLogger.logDebug( message + LINE_SEPARATOR );
      }
      else
      {
          System.out.println( message );
      }
    } // end of log method

}

